package com.lzh.shijicloudstack.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.shijicloudstack.mapper.CookbookCategoryMapper;
import com.lzh.shijicloudstack.mapper.CookbookIngredientMapper;
import com.lzh.shijicloudstack.mapper.CookbookMapper;
import com.lzh.shijicloudstack.mapper.CookbookProcessMapper;
import com.lzh.shijicloudstack.model.dto.cookbook.AddEditCookbookDto;
import com.lzh.shijicloudstack.model.dto.cookbook.CookbookPageDto;
import com.lzh.shijicloudstack.model.entity.Cookbook;
import com.lzh.shijicloudstack.model.entity.CookbookCategory;
import com.lzh.shijicloudstack.model.entity.CookbookIngredient;
import com.lzh.shijicloudstack.model.entity.CookbookProcess;
import com.lzh.shijicloudstack.model.vo.cookbook.CookbookDetailVO;
import com.lzh.shijicloudstack.model.vo.cookbookCategory.CookbookCategoryVO;
import com.lzh.shijicloudstack.model.vo.ingredient.IngredientVO;
import com.lzh.shijicloudstack.service.CookbookIngredientService;
import com.lzh.shijicloudstack.service.CookbookProcessService;
import com.lzh.shijicloudstack.service.CookbookService;
import com.lzh.shijicloudstack.template.PageAbstractTemplate;
import com.lzh.shijicloudstack.utils.BeanCopyUtils;
import com.lzh.shijicloudstack.utils.SqlUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜谱服务实现类
 *
 * @author luzhiheng
 * @date 2025-02-12
 */
@Service
public class CookbookServiceImpl extends ServiceImpl<CookbookMapper, Cookbook> implements CookbookService {

    @Resource
    private CookbookProcessMapper cookbookProcessMapper;

    @Resource
    private CookbookProcessService cookbookProcessService;

    @Resource
    private CookbookIngredientMapper cookbookIngredientMapper;

    @Resource
    private CookbookIngredientService cookbookIngredientService;

    @Resource
    private SqlUtil sqlUtil;

    @Resource
    private CookbookCategoryMapper cookbookCategoryMapper;

    @Override
    public Map<String, Object> pageList(CookbookPageDto dto) {
        Map<String, Object> otherQueryMap = new HashMap<>();
        otherQueryMap.put("cookbookCategoryIdList", dto.getCookbookCategoryIdList());
        PageAbstractTemplate template = new PageAbstractTemplate() {
            @Override
            public Integer countTotal() {
                return baseMapper.countList(this.getQueryMap(dto.getPageModel(), otherQueryMap));
            }

            @Override
            public List<Map<String, Object>> queryPageList() {
                List<Map<String, Object>> pageList = baseMapper.pageList(this.queryMap);
                return pageList;
            }
        };
        return template.queryPage();
    }

    @Override
    public CookbookDetailVO findDetail(Long id) {
        Cookbook cookbook = baseMapper.selectById(id);
        CookbookDetailVO cookbookDetailVO = BeanCopyUtils.copyBean(cookbook, CookbookDetailVO.class);

        // 制作流程列表
        List<CookbookProcess> cookbookProcessList = cookbookProcessMapper.selectByCookbookId(id);
        cookbookDetailVO.setCookbookProcessList(cookbookProcessList);

        // 食材列表
        List<IngredientVO> ingredientVOList = cookbookIngredientMapper.selectByCookbookId(id);
        cookbookDetailVO.setIngredientVOList(ingredientVOList);

        // 菜谱分类列表
        String category = cookbook.getCategory();
        if (StrUtil.isNotEmpty(category)) {
            List<Long> cookbookCategoryIdList = JSON.parseArray(category, Long.class);
            List<CookbookCategory> cookbookCategoryList = cookbookCategoryMapper.selectByIdList(cookbookCategoryIdList);
            List<CookbookCategoryVO> cookbookCategoryVOList = cookbookCategoryList.stream().map(e -> {
                CookbookCategoryVO cookbookCategoryVO = BeanCopyUtils.copyBean(e, CookbookCategoryVO.class);
                cookbookCategoryVO.setLabel(e.getName());
                cookbookCategoryVO.setValue(e.getId());
                return cookbookCategoryVO;
            }).collect(Collectors.toList());
            cookbookDetailVO.setCookbookCategoryList(cookbookCategoryVOList);
        }

        return cookbookDetailVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean add(AddEditCookbookDto dto) {
        Cookbook cookbook = BeanCopyUtils.copyBean(dto, Cookbook.class);
        cookbook.setCategory(JSON.toJSONString(dto.getCookbookCategoryIdList()));
        // 插入菜谱基础信息
        baseMapper.insert(cookbook);
        // 更新菜谱食材
        updateCookbookIngredient(dto, cookbook);
        // 更新菜谱制作流程
        updateCookbookProcess(dto, cookbook);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean edit(AddEditCookbookDto dto) {
        Cookbook cookbook = BeanCopyUtils.copyBean(dto, Cookbook.class);
        cookbook.setCategory(JSON.toJSONString(dto.getCookbookCategoryIdList()));
        // 更新菜谱基础信息
        sqlUtil.executeUpdateSql(sqlUtil.getUpdateSql(cookbook));
        // 更新菜谱食材
        updateCookbookIngredient(dto, cookbook);
        // 更新菜谱制作流程
        updateCookbookProcess(dto, cookbook);
        return true;
    }

    private void updateCookbookIngredient(AddEditCookbookDto dto, Cookbook cookbook) {
        // 删除食材
        cookbookIngredientMapper.deleteByCookbookId(cookbook.getId());
        // 插入食材
        List<IngredientVO> ingredientVOList = dto.getIngredientVOList();
        if (CollectionUtil.isEmpty(ingredientVOList)) {
            return;
        }
        List<CookbookIngredient> cookbookIngredientList = ingredientVOList.stream()
                .map(e -> new CookbookIngredient() {{
                    setCookbookId(cookbook.getId());
                    setIngredientId(e.getId());
                    setIngredientUsage(e.getIngredientUsage());
                }}).collect(Collectors.toList());
        cookbookIngredientService.saveBatch(cookbookIngredientList);
    }

    private void updateCookbookProcess(AddEditCookbookDto dto, Cookbook cookbook) {
        // 删除制作流程
        cookbookProcessMapper.deleteByCookbookId(cookbook.getId());
        // 插入制作流程
        List<CookbookProcess> cookbookProcessList = dto.getCookbookProcessList();
        if (CollectionUtil.isEmpty(cookbookProcessList)) {
            return;
        }
        cookbookProcessList.forEach(e -> {
            e.setCookbookId(cookbook.getId());
            e.setId(null);
        });
        cookbookProcessService.saveBatch(cookbookProcessList);
    }
}
